import { PureComponent } from 'react';
import {
  Scene, BufferGeometry, Vector3, OrthographicCamera,
  MeshBasicMaterial, Mesh, WebGLRenderer, LineBasicMaterial,
  Line
} from 'three';

const drawAxes = scene => {
  const xGeo = new BufferGeometry();
  const xGeoPoints = [
    new Vector3(0, 0, 0),
    new Vector3(4, 0, 0)
  ];
  xGeo.setFromPoints(xGeoPoints);
  const xMat = new LineBasicMaterial({
    color: 0xff0000
  });
  const xAxis = new Line(xGeo, xMat);
  scene.add(xAxis);

  const yGeo = new BufferGeometry();
  const yGeoPoints = [
    new Vector3(0, 0, 0),
    new Vector3(0, 4, 0)
  ];
  yGeo.setFromPoints(yGeoPoints);
  const yMat = new LineBasicMaterial({
    color: 0x00ff00
  });
  const yAxis = new Line(yGeo, yMat);
  scene.add(yAxis);

  const zGeo = new BufferGeometry();
  const zGeoPoints = [
    new Vector3(0, 0, 0),
    new Vector3(0, 0, 4)
  ];
  zGeo.setFromPoints(zGeoPoints);
  const zMat = new LineBasicMaterial({
    color: 0x00ccff
  });
  const zAxis = new Line(zGeo, zMat);
  scene.add(zAxis);
};

class Index extends PureComponent {

  componentDidMount() {
    const scene = new Scene();

    const camera = new OrthographicCamera(-5, 5, 3.75, -3.75, 0.1, 100);
    camera.position.set(25, 25, 25);
    camera.lookAt(0, 0, 0);

    drawAxes(scene);

    const geo = new BufferGeometry();
    // 设置顶点位置
    const geoPoints = [
      // 顶部4顶点
      new Vector3(-1, 2, -1),
      new Vector3(1, 2, -1),
      new Vector3(1, 2, 1),
      new Vector3(-1, 2, 1),
      // 底部4顶点
      new Vector3(-2, 0, -2),
      new Vector3(2, 0, -2),
      new Vector3(2, 0, 2),
      new Vector3(-2, 0, 2)
    ];
    // 设置顶点连接情况
    const faces = [
      // 顶面
      0, 1, 3,
      1, 2, 3,
      // 底面
      4, 5, 6,
      5, 6, 7,
      // 四个侧面
      1, 5, 6,
      6, 2, 1,
      2, 6, 7,
      7, 3, 2,
      3, 7, 0,
      7, 4, 0,
      0, 4, 5,
      0, 5, 1
    ];
    geo.setFromPoints(geoPoints);
    geo.setIndex(faces);

    const material = new MeshBasicMaterial({
      color: 0xffff00,
      wireframe: true
    });

    const mesh = new Mesh(geo, material);
    scene.add(mesh);

    const canvas = document.getElementById('mainCanvas');

    const renderer = new WebGLRenderer({ canvas });
    renderer.render(scene, camera);
  }

  render() {

    return (
      <canvas
        id="mainCanvas"
        width="400"
        height="300"
      />
    );
  }
}

export default Index;